package edu.whu.springdatademo.service.impl;

import edu.whu.springdatademo.dao.ProductRepository;
import edu.whu.springdatademo.entity.Product;
import edu.whu.springdatademo.entity.Supplier;
import edu.whu.springdatademo.exception.ProductException;
import edu.whu.springdatademo.service.ProductService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.persistence.criteria.Predicate;

@Service
public class ProductServiceImpl implements ProductService {

    private final ProductRepository repository;


    public ProductServiceImpl(ProductRepository repository) {
        this.repository = repository;
    }
    @Override
    public Product selectById(Integer id){

        Optional<Product> product = repository.findById(id);



        return product.get();
    }
    @Override
    public Product save(Product product){
        return repository.save(product);
    }
    @Override
    public void deleteById(Integer id) throws ProductException {
        try {
            repository.deleteById(id);
        }catch (Exception e){
            throw  new ProductException("删除的商品未找到！");
        }
    }

    @Override
    public List<Product> SelectByCondition(Map<String, Object> condition) {
        return repository.findAll((root, query, cb) ->{

            List<Predicate> pList = new ArrayList<>();
            if (condition.containsKey("name")) {
                pList.add(cb.like(root.get("name"), "%" + condition.get("name") + "%"));
            }
            if (condition.containsKey("price")) {
                pList.add(cb.le(root.get("price"), (float) condition.get("price")));
            }

            if (condition.containsKey("count")) {
                pList.add(cb.ge(root.get("count"), (int)condition.get("count")));
            }

            if (condition.containsKey("sales")) {
                pList.add(cb.ge(root.get("sales"), (int)condition.get("sales")));
            }
            return cb.and(pList.toArray(new Predicate[0]));
        });
    }

    @Override
    public List<Supplier> selectSuppliers(int pid) {
        return repository.selectSuppliers(pid);
    }


}
